﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace Fish_Atlantis.CustomerPanel
{
    public partial class MessageCenter : System.Web.UI.Page
    {
        protected static PagedDataSource ps = new PagedDataSource();//创建一个分页数据源的对象且一定要声明为静态
        protected static PagedDataSource ps2 = new PagedDataSource();
        static string sqlMessageType = "3";//消息类型默认为3，即单发  
        static string sqlReceiverID = "1";
        static int curpage = 0, comcurpage = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Session["UserID"] != null)
                {
                    string nowUserID = Session["UserID"].ToString();//获取当前用户ID
                    string nowUserType = Helper.ExecuteScalar("select User_Type from Users where UserID = '" + nowUserID + "'");//从Users表获取用户ID对应的用户Type
                    if (nowUserType != "3")//若用户类型不为3（专家），即群发按钮不可见，不可以群发
                    {
                        this.btnSendMutiple.Visible = false;
                    }
                    Page.DataBind();
                    tbSendTo.Items.Insert(0, "请选择");
                    tbSendTo.SelectedIndex = 0;
                    DropDownList1.Items.Insert(0, "请选择");
                    DropDownList1.SelectedIndex = 0;
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>alert('您还未登录，请登录后再操作！！');location.href='/Account/Login.aspx';</script>");
                }

                Bind(curpage);//数据绑定
                commonBind(comcurpage);
            }
        }


        protected void SendBt_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/SendMessage.aspx");
        }

        protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        protected void DataList1_DeleteCommand(object source, DataListCommandEventArgs e)
        {

        }

        protected void ReplyBt0_Click(object sender, EventArgs e)
        {

        }

        protected void btnSendSingle_Click(object sender, EventArgs e)
        {
            this.lblSendTo.Text = "发送对象:";
            this.tbSendTo.Visible = true;
            sqlMessageType = "3";//消息类型，不变
        }

        protected void btnSendMutiple_Click(object sender, EventArgs e)
        {

            this.lblSendTo.Text = "系统群发，慎言慎行";
            this.tbSendTo.Visible = false;
            sqlMessageType = "2";//消息类型变为2
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            if (Session["UserID"] != null)
            {
                string sqlFisheryID;
                string sqlSenderID = Session["UserID"].ToString();
                if (this.DropDownList1.SelectedValue.ToString() == "请选择")
                {

                }

                if (sqlMessageType == "2")//群发，ReceiverID为null，不用Insert
                {
                    if (this.tbContent.Text.Trim() == "") Response.Write("<script language=javascript>alert('" + "内容不能为空，请填写发送内容。" + "')</script>");
                    else
                    {
                        if (this.DropDownList1.SelectedValue.ToString() == "请选择")
                        {

                            Helper.ExecSQL("insert into Message(SenderID,Content_Text,Time,Message_Type) values('" + sqlSenderID + "','" + this.tbContent.Text.Trim() + "','" + System.DateTime.Now.ToString() + "','" + sqlMessageType + "')");
                            Response.Write("<script language=javascript>alert('" + "发送成功" + "')</script>");
                        }
                        else
                        {
                            sqlFisheryID = Helper.ExecuteScalar("select FisheryID from Fishery where FisheryName = '" +
                                                               this.DropDownList1.SelectedValue.ToString() + "';");
                            Helper.ExecSQL("insert into Message(FisheryID,SenderID,Content_Text,Time,Message_Type) values('" + sqlFisheryID + "','" + sqlSenderID + "','" + this.tbContent.Text.Trim() + "','" + System.DateTime.Now.ToString() + "','" + sqlMessageType + "')");
                            Response.Write("<script language=javascript>alert('" + "发送成功" + "')</script>");
                        }
                    }

                }
                else if (sqlMessageType == "3")//单发，ReceiverID为输入ID
                {
                    try
                    {
                        if (this.tbContent.Text.Trim() == "") Response.Write("<script language=javascript>alert('" + "内容不能为空，请填写发送内容。" + "')</script>");
                        else
                        {
                            if (this.DropDownList1.SelectedValue.ToString() == "请选择")
                            {

                                sqlReceiverID = Helper.ExecuteScalar("select UserID from Users where UserName = '" + this.tbSendTo.Text.Trim() + "'");//从User表获取用户名称对应的用户ID
                                Helper.ExecSQL("insert into Message(SenderID,ReceiverID,Content_Text,Time,Message_Type) values('" + sqlSenderID + "','" + sqlReceiverID + "','" + this.tbContent.Text.Trim() + "','" + System.DateTime.Now.ToString() + "','" + sqlMessageType + "')");
                                Response.Write("<script language=javascript>alert('" + "发送成功" + "')</script>");
                            }
                            else
                            {
                                sqlFisheryID = Helper.ExecuteScalar("select FisheryID from Fishery where FisheryName = '" +
                                                               this.DropDownList1.SelectedValue.ToString() + "';");
                                sqlReceiverID = Helper.ExecuteScalar("select UserID from Users where UserName = '" + this.tbSendTo.Text.Trim() + "'");//从User表获取用户名称对应的用户ID
                                Helper.ExecSQL("insert into Message(FisheryID,SenderID,ReceiverID,Content_Text,Time,Message_Type) values('" + sqlFisheryID + "','" + sqlSenderID + "','" + sqlReceiverID + "','" + this.tbContent.Text.Trim() + "','" + System.DateTime.Now.ToString() + "','" + sqlMessageType + "')");
                                Response.Write("<script language=javascript>alert('" + "发送成功" + "')</script>");
                            }
                        }
                    }
                    catch (Exception error)
                    {
                        //Response.Write(error.Message);//显示未将对象引用至对象实例
                        Response.Write("<script language=javascript>alert('" + "发送失败！请正确输入发送对象！" + "')</script>");
                    }
                }
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>alert('您还未登录，请登录后再操作！！');location.href='/Account/Login.aspx';</script>");
            }

            //  Bind(0);//数据绑定

        }

        public void Bind(int CurrentPage)
        {
            if (Session["UserID"] != null)
            {
                this.DataList1.DataSourceID = null;
                //实例化数据集DataSet

                DataSet ds = new DataSet();
                ds = Helper.GetDataSet("SELECT MessageID,y.UserName, Message.FisheryID, Message.Content_Text, convert(varchar(10),Message.Time,120) Time FROM Message INNER JOIN Users AS y ON Message.SenderID = y.UserID CROSS JOIN Users AS x WHERE (x.UserID = " + Session["UserID"].ToString() + ") AND Message.ReceiverID = x.UserID ORDER BY Message.Message_Type DESC, Message.Time DESC", "MessageInfo");
                ps.DataSource = ds.Tables["MessageInfo"].DefaultView;
                ps.AllowPaging = true; //是否可以分页
                ps.PageSize = 4; //显示的数量
                ps.CurrentPageIndex = curpage; //取得当前页的页码

                this.DataList1.DataSource = ps;
                //  this.DataList1.DataKeyField = "MessageID";
                this.DataList1.DataBind();
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>alert('您还未登录，请登录后再操作！！');location.href='/Account/Login.aspx';</script>");
            }
        }

        public void commonBind(int CurrentPage)
        {
            if (Session["UserID"] != null)
            {
                this.DataList2.DataSourceID = null;
                //实例化数据集DataSet

                DataSet ds = new DataSet();
                ds = Helper.GetDataSet("select Message.MessageID,y.UserName,Message.Content_Text,Message.Time from Message,Users y where  Message.ReceiverID is null and Message.SenderID=y.UserID order by Message.Message_Type asc,Message.Time desc;", "MessageInfo");
                ps2.DataSource = ds.Tables["MessageInfo"].DefaultView;
                ps2.AllowPaging = true; //是否可以分页
                ps2.PageSize = 5; //显示的数量
                ps2.CurrentPageIndex = comcurpage; //取得当前页的页码

                this.DataList2.DataSource = ps2;
                //  this.DataList1.DataKeyField = "MessageID";
                this.DataList2.DataBind();
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>alert('您还未登录，请登录后再操作！！');location.href='/Account/Login.aspx';</script>");
            }
        }

        protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (Session["UserID"] != null)
            {
                TextBox tb = (TextBox)e.Item.FindControl("TextBox2");
                LinkButton ub = e.Item.FindControl("UserButton1") as LinkButton;
                string sqlSenderID = Session["UserID"].ToString();
                sqlMessageType = "3";
                switch (e.CommandName)
                {
                    case "reply":
                        {
                            if (tb.Text.Trim() == "" || tb.Text.Trim() == "请在此填写回复内容...")
                            {
                                Response.Write(Helper.MessageBox("请填写回复内容。"));

                                //   Bind(0);//数据绑定

                            }
                            else try
                                {
                                    sqlReceiverID = Helper.ExecuteScalar("select UserID from Users where UserName = '" + ub.Text.Trim() + "'");//从User表获取用户名称对应的用户ID
                                    Helper.ExecSQL("insert into Message(SenderID,ReceiverID,Content_Text,Time,Message_Type) values('" + sqlSenderID + "','" + sqlReceiverID + "','" + tb.Text.Trim() + "','" + System.DateTime.Now.ToString() + "','" + sqlMessageType + "')");
                                    Response.Write("<script language=javascript>alert('" + "发送成功" + "')</script>");

                                    //        Bind(0);//数据绑定

                                }
                                catch (Exception error)
                                {
                                    //Response.Write(error.Message);//显示未将对象引用至对象实例
                                    Response.Write("<script language=javascript>alert('" + "发送失败！请正确输入发送对象！" + "')</script>");
                                }
                        }
                        break;//以下5个为 捕获用户点击 上一页 下一页等时发生的事件
                    case "delete":
                        Label Meid = e.Item.FindControl("MessageID") as Label;
                        try
                        {
                            Helper.ExecSQL("delete from message where MessageID='" + Meid.Text.Trim() + "';");
                            Response.Write("<script language=javascript>alert('" + "删除成功" + "')</script>");
                            Bind(curpage);
                        }
                        catch
                        {
                            Response.Write("<script language=javascript>alert('" + "由于数据库的原因，删除失败！" + "')</script>");
                        }
                        break;
                    case "first"://第一页                   
                        curpage = 0;
                        Bind(curpage);
                        break;
                    case "pre"://上一页
                        curpage--;
                        Bind(curpage);
                        break;
                    case "next"://下一页
                        curpage++;
                        Bind(curpage);
                        break;
                    case "last"://最后一页
                        curpage = ps.PageCount - 1;
                        Bind(curpage);
                        break;
                }
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>alert('您还未登录，请登录后再操作！！');location.href='/Account/Login.aspx';</script>");
            }
        }

        protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item)
            {
                Label fishLb = e.Item.FindControl("FisheryID") as Label;
                Label fisheryName = e.Item.FindControl("FisheryLabel") as Label;
                if (fishLb.Text.Trim() == "NULL" || fishLb.Text.Trim() == "") fisheryName.Text = "";
                else
                {
                    string fishstr = Helper.ExecuteScalar("select fisheryName from fishery where FisheryID='" + fishLb.Text.Trim() + "';");
                    fisheryName.Text = fishstr;
                }
            }
            if (e.Item.ItemType == ListItemType.Footer)
            {
                //以下六个为得到脚模板中的控件,并创建变量
                Label CurrentPage = e.Item.FindControl("labNowPage") as Label;
                Label PageCount = e.Item.FindControl("labCount") as Label;
                LinkButton FirstPage = e.Item.FindControl("lnkbtnFirst") as LinkButton;
                LinkButton PrePage = e.Item.FindControl("lnkbtnFront") as LinkButton;
                LinkButton NextPage = e.Item.FindControl("lnkbtnNext") as LinkButton;
                LinkButton LastPage = e.Item.FindControl("lnkbtnLast") as LinkButton;
                CurrentPage.Text = (ps.CurrentPageIndex + 1).ToString();//绑定显示当前页
                PageCount.Text = ps.PageCount.ToString();//绑定显示总页数
                if (ps.IsFirstPage)//如果是第一页,首页和上一页不能用
                {
                    FirstPage.Enabled = false;
                    PrePage.Enabled = false;
                }
                if (ps.IsLastPage)//如果是最后一页"下一页"和"尾页"按钮不能用
                {
                    NextPage.Enabled = false;
                    LastPage.Enabled = false;
                }
            }
        }

        protected void DataList2_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (Session["UserID"] != null)
            {
                switch (e.CommandName)
                {
                    case "first"://第一页                   
                        comcurpage = 0;
                        commonBind(comcurpage);
                        break;
                    case "pre"://上一页
                        comcurpage--;
                        commonBind(comcurpage);
                        break;
                    case "next"://下一页
                        comcurpage++;
                        commonBind(comcurpage);
                        break;
                    case "last"://最后一页
                        comcurpage = ps2.PageCount - 1;
                        commonBind(comcurpage);
                        break;
                }
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script language='javascript'>alert('您还未登录，请登录后再操作！！');location.href='/Account/Login.aspx';</script>");
            }
        }

        protected void DataList2_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                //以下六个为得到脚模板中的控件,并创建变量
                Label CurrentPage = e.Item.FindControl("labNowPage") as Label;
                Label PageCount = e.Item.FindControl("labCount") as Label;
                LinkButton FirstPage = e.Item.FindControl("lnkbtnFirst") as LinkButton;
                LinkButton PrePage = e.Item.FindControl("lnkbtnFront") as LinkButton;
                LinkButton NextPage = e.Item.FindControl("lnkbtnNext") as LinkButton;
                LinkButton LastPage = e.Item.FindControl("lnkbtnLast") as LinkButton;
                CurrentPage.Text = (ps2.CurrentPageIndex + 1).ToString();//绑定显示当前页
                PageCount.Text = ps2.PageCount.ToString();//绑定显示总页数
                if (ps2.IsFirstPage)//如果是第一页,首页和上一页不能用
                {
                    FirstPage.Enabled = false;
                    PrePage.Enabled = false;
                }
                if (ps2.IsLastPage)//如果是最后一页"下一页"和"尾页"按钮不能用
                {
                    NextPage.Enabled = false;
                    LastPage.Enabled = false;
                }
            }
            if (e.Item.ItemType == ListItemType.Item)
            {
                Label idLb = e.Item.FindControl("Label2") as Label;
                string messageType = Helper.ExecuteScalar("select Message_Type from  Message where MessageID=" + idLb.Text.Trim() + ";");
                if (messageType == "1") e.Item.ForeColor = System.Drawing.Color.Red;
            }
        }


    }
}